package com.metagurukul.metagranth.actionservlets;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.metagurukul.metagranth.service.QuestionService;
import com.metagurukul.metagranth.vo.MetaData;

/**
 * This servlet is responsible for handling the functionality of Edit Questions.
 * It will display all the questions which are editable ,that is, which are posted by the user currently logged in
 * And those questions which do not have any answer.
 * 
 * @author team MetaGranth
 *
 */
public class EditQuestionsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public EditQuestionsServlet() {
        super();

    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}
	
	/**
	 * this function will gets the userId of the user currently logged in to the system.
	 * Calls the getEditableQuestions function in the QuestionService Service Layer 
	 * which are editable ,that is, which are posted by the user currently logged in 
	 * And those questions which do not have any answer.
	 * It will return the metaDataList of those questions and will dispatch the same to the editableQuestionsDisplay.jsp page
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doPerform(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		if(session.getAttribute("userId")!=null){
		// gets the userId of the user currently logged in
		int userId=Integer.parseInt(session.getAttribute("userId").toString());
		try {
			ArrayList<MetaData> metaDataList = QuestionService.getEditableQuestions(userId);
			request.setAttribute("metaDataList", metaDataList);
			request.getRequestDispatcher("editableQuestionsDisplay.jsp").forward(request, response);
		} catch (Exception exception) {
			request.setAttribute("errormsg", exception.getMessage());
			request.getRequestDispatcher("errorPage.jsp").forward(request, response);
		}		
		}else {
			response.sendRedirect("index.jsp");
		}
		
	}

}
